import { LogLevel } from "./LogLevel"
import { MakeMessage } from "./MakeMessage"
import hilog from "@ohos.hilog"


export class Logger {
  static DEFAULT_TYPE = 1
  private readonly tag: string
  private readonly type: number
  private readonly makeMessage: MakeMessage

  constructor(tag: string, makeMessage: MakeMessage) {
    let temp = tag.split("---type---")
    this.tag = temp[0]
    this.type = parseInt(temp[1])
    this.makeMessage = makeMessage
  }

  /**
   * 打印一条DEBUG级别的日志
   * @param format 日志格式
   * @param args 日志参数
   */
  debug(format: string, ...args: Array<string | object | number>) {
    this.print(LogLevel.DEBUG, format, args);
  }

  /**
   * 打印一条ERROR级别的日志
   * @param format 日志格式
   * @param args 日志参数
   */
  error(format: string, ...args: Array<string | object | number>) {
    this.print(LogLevel.ERROR, format, args);
  }

  /**
   * 打印一条WARN级别的日志
   * @param format 日志格式
   * @param args 日志参数
   * @since 1.5.4
   */
  warn(format: string, ...args: Array<string | object | number>) {
    this.print(LogLevel.WARN, format, args);
  }

  /**
   * 打印一条INFO级别的日志
   * @param format 日志格式
   * @param args 日志参数
   */
  info(format: string, ...args: Array<string | object | number>) {
    this.print(LogLevel.INFO, format, args);
  }

  /**
   * 打印一条FATAL级别的日志
   * @param format 日志格式
   * @param args 日志参数
   */
  fatal(format: string, ...args: Array<string | object | number>) {
    this.print(LogLevel.FATAL, format, args);
  }

  /**
   * 打印一条INFO级别的日志
   * @param format 日志格式
   * @param args 日志参数
   */
  log(format: string, ...args: Array<string | object | number>) {
    this.info(format, ...args)
  }

  private print(level: LogLevel, format: string, args: Array<string | object | number>) {
    let message = this.makeMessage.makeMessage(format, args)
    this.hilog(level, message)
    this.writeFile(this.type, this.tag, message)
  }

  private writeFile(_: number, ___: string, __: string) {
    hilog.warn(0x00F2, "Logan", "Write operation aborted due to component method error")
  }

  private hilog(level: LogLevel, message: string) {
    let count = Math.floor(message.length / 1024)
    for (let i = 0; i <= count; i++) {
      this.getHilogFunction(level)(0x00F1, this.tag, message.substring(i * 1024, (i + 1) * 1024))
    }
  }

  private getHilogFunction(lvl: LogLevel): Function {
    if (lvl == LogLevel.ERROR) {
      return hilog.error;
    } else if (lvl == LogLevel.WARN) {
      return hilog.warn;
    } else if (lvl == LogLevel.DEBUG) {
      return hilog.debug;
    } else if (lvl == LogLevel.FATAL) {
      return hilog.fatal;
    }
    return hilog.info;
  }
}